package net.fdukedom.epicurus.webinit;

import net.fdukedom.epicurus.domain.entity.Plugin;
import net.fdukedom.epicurus.domain.util.HibernateUtil;
import net.fdukedom.epicurus.plugin.AbstractPluginLoader;
import net.fdukedom.epicurus.plugin.FilePluginLoader;
import net.fdukedom.epicurus.plugin.PluginRegistrar;
import net.fdukedom.epicurus.tools.logging.Logger;
import net.fdukedom.epicurus.tools.logging.WriterId;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import java.io.FileNotFoundException;
import java.util.List;

/**
 * Configures application on server start up.
 *
 * @author Dmitry Y. Kochelaev
 */
public class ConfigServlet extends HttpServlet {

    public void init() throws ServletException {
        super.init();
        //loading all plug-in's
        try {
            HibernateUtil.newSession();
            AppEnvironment.setAppFolder(this.getServletContext().getRealPath(""));
            AbstractPluginLoader pluginLoader = new FilePluginLoader(AppEnvironment.getPluginFolder());
            List<Plugin> plugins = pluginLoader.loadPlugins();
            PluginRegistrar.register(plugins);
        } catch (FileNotFoundException e) {
            Logger.getInstance(WriterId.PLUGIN_LOADER).logError("Plug-in folder not found");
        } finally {
            HibernateUtil.closeSession();
        }
    }
}
